<template>
  <div>
    <el-row align="middle" justify="center" style="height: 80px">
      <p style="fontSize: 30px; font-weight: bold;">
        孕妇体征检测
      </p>
    </el-row>
    <el-row :gutter="5" justify="end" align="middle" style="margin-bottom: 6px;">
      <el-col :span="6">
        <el-input type="text" v-model="chip_id" placeholder="请输入设备id" clearable ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="submitChipId">提交</el-button>
      </el-col>
    </el-row>
    <el-card class="box-card" style="margin-bottom: 8px">
      <el-row :gutter="0" justify="center" align="middle" style="">
        <el-col :span="20">
          <div id="hrChart" style="height: 360px"></div>
        </el-col>
        <el-col :span="3">
          <p style="fontSize: 100px">
            {{ latestHr }}
          </p>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card" style="margin-bottom: 8px">
      <el-row :gutter="0" justify="center" align="middle" style="">
        <el-col :span="20">
          <div id="brChart" style="height: 360px"></div>
        </el-col>
        <el-col :span="3">
          <p style="fontSize: 100px">
            {{ latestBr }}
          </p>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card">
      <!-- <el-row :gutter="0" justify="center" align="middle" style="">
        <el-col :span="20">
          <div id="hrvChart" style="height: 370px"></div>
        </el-col>
        <el-col :span="3">
          <el-image
            style="width: 100px; height: 100px"
            src="https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"
            :fit="fill"
          ></el-image>
        </el-col>
      </el-row> -->
      <div id="hrvChart" style="height: 370px"></div>
    </el-card>
  </div>
</template>
<script>
import { ElMessage } from 'element-plus'
import common from '../js/common'
import fdata from '../js/fdata'

export default {
  name: 'PresentationDashboard',
  components: {},
  props: [],
  data () {
    return {
      chip_id: '3F286F24',   // 5F08E509
      button_click: false,
      timer: common.setMyInterval(function(){}, 60000),
      show_timer: common.setMyInterval(function(){}, 60000),
      hrChart: 0,
      brChart: 0,
      hrvChart: 0,
      latestHr: '--',
      latestBr: '--',
      latestHrv: '--'
    }
  },
  computed: {},
  watch: {
    button_click: {
      handler: function () {
        common.clearMyInterval(this.timer)
        common.clearMyInterval(this.show_timer)
        const REFRESH_INTERVAL = 1000 * 20
        const new_chip_id = this.chip_id
        
        this.hrChart.clear()
        this.brChart.clear()
        this.hrvChart.clear()
        const hrChart = this.hrChart
        const brChart = this.brChart
        const hrvChart = this.hrvChart

        function buildDataToPlot(dataList) {
          let dataToPlot = []
          for(let i=0; i<dataList.length; i++) {
            dataToPlot.push([i, parseFloat(dataList[i])])
          }
          return dataToPlot
        }

        function sleep(n) {
          n *= 1000
          let start = new Date().getTime();
          //  console.log('休眠前：' + start);
          while (true) {
              if (new Date().getTime() - start > n) {
                  break;
              }
          }
        }

        let startTime = Date.parse(new Date())//获取到毫秒的时间戳，精确到毫秒
        // let startTime = Date.parse(new Date(2021, 11, 10, 16, 37))    //temp test interface

        let prevSegmentId = -1
        let hrList=[], brList=[], hrvList=[], latestHrv=-1
        let xDataHrvList = []
        let hrData = []
        let brData = []
        let hrDataToPlot=[], brDataToPlot=[]

        if (new_chip_id === '5F08E509') {
          // example plot
          //init presentation data
          let globalMeanRateIndex = -1
          console.log("Init processing...")

          hrList = fdata.hrList
          brList = fdata.brList
          this.latestHr = '--'
          this.latestBr = '--'
          this.latestHrv = '--'
          hrData = hrList.slice(0, 500)
          hrList = hrList.slice(500, hrList.length)
          hrDataToPlot = buildDataToPlot(hrData) 
          brData = brList.slice(0, 500)
          brList = brList.slice(500, brList.length)
          brDataToPlot = buildDataToPlot(brData)
          // console.log(hrDataToPlot)

          // 模拟等待从服务器获取数据
          sleep(5)

          console.log('Init finished!')
          ElMessage({
            message: '获取最新数据成功',
            type: 'success',
          })

          const hrOption = {
            title: {
              text: '心跳',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              // type: 'time',
              // data: xData,
              show: false,
              splitLine: {
                show: false
              }
            },
            yAxis: {
              // type: 'value',
              // min: -2300,
              // max: 2300,
              show: false,
              // boundaryGap: [0, '100%']
            },
            series: [
              {
                name: '心跳波形',
                type: 'line',
                showSymbol: false,
                data: hrDataToPlot
              }
            ]
          }

          const brOption = {
            title: {
              text: '呼吸',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              // type: 'time',
              // data: xData,
              show: false,
              splitLine: {
                show: false
              }
            },
            yAxis: {
              // type: 'value',
              // min: -2300,
              // max: 2300,
              show: false,
              // boundaryGap: [0, '100%'],
            },
            series: [
              {
                name: '呼吸波形',
                type: 'line',
                showSymbol: false,
                data: brDataToPlot
              }
            ]
          }

          const hrvOption = {
            title: {
              text: 'HRV',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              type: 'category',
              data: [0, 1, 2, 3, 4, 5, 6],
              show: false
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                show: false
              }
            },
            series: [
              {
                data: hrvList,
                type: 'line',
                smooth: true
              }
            ]
          }

          this.timer = common.setMyInterval(() => {
            //缓冲区更新
            console.log("Updating buffer...")
            globalMeanRateIndex += 1
            this.latestHr = parseInt(fdata.meanHrList[globalMeanRateIndex])
            this.latestBr = parseInt(fdata.meanBrList[globalMeanRateIndex])
            this.latestHrv = parseInt(fdata.hrvList[globalMeanRateIndex])
            if (this.latestHr === -1) this.latestHr = '--'
            if (this.latestBr === -1) this.latestBr = '--'
            if (this.latestHrv === -1) this.latestHrv = '--'
            // if (hrvList.length >= 7) {
            //   hrvList.shift()
            // }
            // update buffer
            hrvList.push(this.latestHrv)
            xDataHrvList.push(globalMeanRateIndex)
            console.log("Update buffer success!")
            ElMessage({
              message: '获取最新数据成功',
              type: 'success',
            })
            hrvChart.setOption({
              xAxis: {
                data: xDataHrvList
              },
              series: [
                {
                  data: hrvList
                }
              ]
            })
          }, REFRESH_INTERVAL)

          this.show_timer = common.setMyInterval(() => {
            let freshPoint = 1   //每个Interval刷新的点的数量
            hrData = hrData.slice(freshPoint, 1000)
            hrData = hrData.concat(hrList.slice(0, freshPoint))
            hrList = hrList.slice(freshPoint, hrList.length)
            hrDataToPlot = buildDataToPlot(hrData)
            brData = brData.slice(freshPoint, 1000)
            brData = brData.concat(brList.slice(0, freshPoint))
            brList = brList.slice(freshPoint, brList.length)
            brDataToPlot = buildDataToPlot(brData)
            hrChart.setOption({
              series: [
                {
                  data: hrDataToPlot
                }
              ]
            })
            brChart.setOption({
              series: [
                {
                  data: brDataToPlot
                }
              ]
            })
          }, 20)

          hrChart.setOption(hrOption)
          brChart.setOption(brOption)
          hrvChart.setOption(hrvOption)
        } else {
          // realtime streaming
          //init presentation data
          console.log("Init processing...")
          common.getRealtimeData(new_chip_id, startTime)
          .then(response => {
            if (response && response.result == '200') {
              // console.log(response)
              hrList = eval(eval(response.data.list.hr_list))
              brList = eval(eval(response.data.list.br_list))
              this.latestHr = Math.round(response.data.list.hr)
              this.latestBr = Math.round(response.data.list.br)
              this.latestHrv = parseInt(response.data.list.hrv_list)
              if (this.latestHr === -1) this.latestHr = '--'
              if (this.latestBr === -1) this.latestBr = '--'
              if (this.latestHrv === -1) this.latestHrv = '--'
              hrData = hrList.slice(0, 500)
              hrList = hrList.slice(500, hrList.length)
              hrDataToPlot = buildDataToPlot(hrData) 
              brData = brList.slice(0, 500)
              brList = brList.slice(500, brList.length)
              brDataToPlot = buildDataToPlot(brData)
              hrvList.push(this.latestHrv)
              // console.log(hrDataToPlot)
              startTime = response.data.list.start_time
              prevSegmentId = parseInt(response.data.list.id)
              ElMessage({
                message: '获取最新数据成功',
                type: 'success',
              })
              // console.log("Record start time is", startTime)
            } else {
              alert("初始化获取数据失败, 请刷新页面重试")
            }
          })
          .catch(
            err => alert("初始化获取数据失败, 请刷新页面重试", err)
          )

          // 等待从服务器获取数据
          sleep(5)

          console.log('Init finished!')

          const hrOption = {
            title: {
              text: '心跳',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              // type: 'time',
              // data: xData,
              show: false,
              splitLine: {
                show: false
              }
            },
            yAxis: {
              // type: 'value',
              // min: -2300,
              // max: 2300,
              show: false,
              // boundaryGap: [0, '100%']
            },
            series: [
              {
                name: '心跳波形',
                type: 'line',
                showSymbol: false,
                data: hrDataToPlot
              }
            ]
          }

          const brOption = {
            title: {
              text: '呼吸',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              // type: 'time',
              // data: xData,
              show: false,
              splitLine: {
                show: false
              }
            },
            yAxis: {
              // type: 'value',
              // min: -2300,
              // max: 2300,
              show: false,
              // boundaryGap: [0, '100%'],
            },
            series: [
              {
                name: '呼吸波形',
                type: 'line',
                showSymbol: false,
                data: brDataToPlot
              }
            ]
          }

          const hrvOption = {
            title: {
              text: 'HRV',
              left: 'center',
              textStyle: {
                fontSize: 25
              }
            },
            xAxis: {
              type: 'category',
              data: [0, 1, 2, 3, 4, 5, 6],
              show: false
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                show: false
              }
            },
            series: [
              {
                data: hrvList,
                type: 'line',
                smooth: true
              }
            ]
          }

          this.timer = common.setMyInterval(() => {
            //缓冲区更新
            common.getRealtimeData(new_chip_id, startTime)
            .then(response => {
              console.log("Updating buffer...")
              if (response && response.result == '200') {
                  let latestSengmentId = parseInt(response.data.list.id)
                  if (latestSengmentId === prevSegmentId) {
                    alert("获取最新数据失败,请刷新页面")
                  } else {
                    prevSegmentId = latestSengmentId
                    let tempHrList = eval(eval(response.data.list.hr_list))
                    let tempBrList = eval(eval(response.data.list.br_list))
                    this.latestHr = Math.round(response.data.list.hr)
                    this.latestBr = Math.round(response.data.list.br)
                    this.latestHrv = parseInt(response.data.list.hrv_list)
                    if (this.latestHr === -1) this.latestHr = '--'
                    if (this.latestBr === -1) this.latestBr = '--'
                    if (this.latestHrv === -1) this.latestHrv = '--'
                    // if (hrvList.length >= 7) {
                    //   hrvList.shift()
                    // }
                    // update buffer
                    if (this.latestHrv !== -1) {
                      hrvList.push(this.latestHrv)
                    }
                    hrList = hrList.concat(tempHrList.slice(0, tempHrList.length))
                    brList = brList.concat(tempBrList.slice(0, tempBrList.length))
                    console.log("Update buffer success!")
                    ElMessage({
                      message: '获取最新数据成功',
                      type: 'success',
                    })
                    hrvChart.setOption({
                      series: [
                        {
                          data: hrvList
                        }
                      ]
                    })
                  }
              } else {
                alert("网络环境异常，请刷新网页重试")
              }
            })
            .catch(
              err => console.log(err)
            )
          }, REFRESH_INTERVAL)

          this.show_timer = common.setMyInterval(() => {
            let freshPoint = 1   //每个Interval刷新的点的数量
            hrData = hrData.slice(freshPoint, 1000)
            hrData = hrData.concat(hrList.slice(0, freshPoint))
            hrList = hrList.slice(freshPoint, hrList.length)
            hrDataToPlot = buildDataToPlot(hrData)
            brData = brData.slice(freshPoint, 1000)
            brData = brData.concat(brList.slice(0, freshPoint))
            brList = brList.slice(freshPoint, brList.length)
            brDataToPlot = buildDataToPlot(brData)
            hrChart.setOption({
              series: [
                {
                  data: hrDataToPlot
                }
              ]
            })
            brChart.setOption({
              series: [
                {
                  data: brDataToPlot
                }
              ]
            })
          }, 20)

          hrChart.setOption(hrOption)
          brChart.setOption(brOption)
          hrvChart.setOption(hrvOption)
        }
      }
    }
  },
  created () {
  },
  mounted () {
    const hrChartDom = document.getElementById('hrChart')
    this.hrChart = this.$echarts.init(hrChartDom)
    const brChartDom = document.getElementById('brChart')
    this.brChart = this.$echarts.init(brChartDom)
    const hrvChartDom = document.getElementById('hrvChart')
    this.hrvChart = this.$echarts.init(hrvChartDom)
  },
  methods: {
    submitChipId (event) {
      console.log("Chip id: "+this.chip_id)
      this.button_click = ~this.button_click
    },
  }
}

</script>
<style>

</style>
